package me.albert.entitylimiter;

import me.albert.entitylimiter.listeners.ItemListener;
import me.albert.entitylimiter.tasks.ChunkTask;
import me.albert.entitylimiter.utils.inventory.PagedInv;
import me.albert.entitylimiter.utils.inventory.TiHolder;

import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;

public class EntityLimiter extends JavaPlugin {
    private static EntityLimiter instance;

    public static EntityLimiter getInstance() {
        return EntityLimiter.instance;
    }

    public void onEnable() {
        (EntityLimiter.instance = this).saveDefaultConfig();
        this.getServer().getPluginManager().registerEvents(new ItemListener(), this);
        ChunkTask.start();
        this.getLogger().info("Loaded");
    }

    public void onDisable() {
        for (final Player p : Bukkit.getOnlinePlayers()) {
            p.getOpenInventory().getTopInventory();
            if (p.getOpenInventory().getTopInventory().getHolder() instanceof TiHolder) {
                p.closeInventory();
            }
        }
    }

    public boolean onCommand(final CommandSender sender, final Command command, final String label, final String[] args) {
        if (!(sender instanceof Player)) {
            sender.sendMessage("§c玩家才能用");
            return true;
        }
        if (args.length == 1 && args[0].equalsIgnoreCase("trash")) {
            final Player p = (Player) sender;
            if (PagedInv.invs.size() == 0) {
                p.sendMessage("§c没有任何回收的物品");
                p.closeInventory();
                return true;
            }
            int page = 0;
            if (ItemListener.pages.containsKey(p.getUniqueId())) {
                page = ItemListener.pages.get(p.getUniqueId());
            }
            final Inventory first = PagedInv.invs.get(page);
            p.openInventory(first);
        } else {
            if (args.length == 1 && args[0].equalsIgnoreCase("reload") && sender.hasPermission("entitylimiter.reload")) {
                this.reloadConfig();
                sender.sendMessage("§a已重新载入配置文件");
                return true;
            }
            sender.sendMessage("§a/el trash - 打开回收站");
            sender.sendMessage("§a/el reload - 重新载入配置文件");
        }
        return true;
    }
}
